import {
  DEL_TODO,
  CHANGE_DONE,
  ADD_TODO,
  SELECT_ALL,
  EDIT_NAME,
  DEL_COMPLETED,
} from '../constant/todos'

const initState = [
  { id: 1, name: '吃饭', done: false },
  { id: 2, name: '睡觉', done: true },
  { id: 3, name: '打豆豆', done: false },
]
export default function todos(state = initState, action) {
  // 删除
  if (action.type === DEL_TODO) {
    return state.filter((item) => item.id !== action.id)
  }
  // 修改状态
  if (action.type === CHANGE_DONE) {
    return state.map((item) => {
      if (item.id === action.id) {
        return { ...item, done: !item.done }
      } else {
        return item
      }
    })
  }
  // 添加

  if (action.type === ADD_TODO) {
    const obj = { id: action.id, name: action.name, done: false }
    return [obj, ...state]
  }
  // 全选反选
  if (action.type === SELECT_ALL) {
    return state.map((item) => ({ ...item, done: action.done }))
  }
  // 修改
  if (action.type === EDIT_NAME) {
    return state.map((item) => {
      if (item.id === action.id) {
        return { ...item, name: action.name }
      } else {
        return item
      }
    })
  }
  // 清除已完成
  if (action.type === DEL_COMPLETED) {
    return state.filter((item) => !item.done)
  }
  return state
}
